<template>
	<div class="page-container">
		<h1>文本比较器</h1>
		<el-form ref="form" :model="form" label-position="top">
			<el-form-item label="文本A">
				<el-input type="textarea" v-model="form.textA"></el-input>
			</el-form-item>
			<el-form-item label="文本B">
				<el-input type="textarea" v-model="form.textB"></el-input>
			</el-form-item>
		</el-form>
		<el-button type="primary" @click="compare()">比较</el-button>
		<div v-if="result.length > 0">
			<div>
				<p><strong>文本A：</strong></p>
				<div class="text-diff">
					<span v-for="diff in result"
						:class="{ 'diff-added': diff.added, 'diff-removed': diff.removed }">{{ diff.added ? '+' : diff.removed ? '-' : '' }}{{ diff.value }}</span>
				</div>
			</div>
			<div>
				<p><strong>文本B：</strong></p>
				<div class="text-diff">
					<span v-for="diff in result"
						:class="{ 'diff-added': diff.removed, 'diff-removed': diff.added }">{{ diff.removed ? '+' : diff.added ? '-' : '' }}{{ diff.value }}</span>
				</div>
			</div>
		</div>
		
	</div>
</template>

<script>
	const Diff = require('diff');

	export default {
		data() {
			return {
				form: {
					textA: "",
					textB: ""
				},
				result: []
			};
		},
		methods: {
			compare() {
				const textA = this.form.textA;
				const textB = this.form.textB;
				const diff = Diff.diffChars(textA, textB);
				this.result = diff;
			}
		},
	};
</script>

<style>
	.text-diff {
		display: flex;
		flex-wrap: wrap;
	}

	.diff-added {
		background-color: #c8f7c5;
	}

	.diff-removed {
		background-color: #ffcdd2;
	}

	.text-diff span {
		padding: 2px;
		margin: 2px;
	}
</style>
